from datetime import *

def format_sql_criteria(column_name, including_values):
	if (not including_values) or (len(including_values)==0):
		return "1=1"
	#elif len(including_values)==1:
	elif isinstance(including_values,str):
		return column_name + "='" + including_values + "'"
	else:
		ret = column_name + ' in ('
		is_first_elem = True
		for elem in including_values:
			if is_first_elem:
				ret += "'" + elem + "'"
				is_first_elem = False
			else:
				ret += ",'" + elem + "'"
		ret += ')'
		return ret
		
def format_sql_tick_criteria(column_name, tick_list):
	
	if tick_list:
		ret = ',('
		is_first_elem = True
		for elem in tick_list:
			if is_first_elem:
				ret += "(select '" + elem + "' tick from dual)"
				is_first_elem = False
			else:
				ret += " union (select '" + elem + "' tick from dual)"
		ret += ') tick_tb where tick_tb.tick = ' + column_name
		return ret
	else:
		return 'where 1 = 1'
		
def offset_date_by_month(d, offset_months):
	one_day = timedelta(days=1)
	q,r = divmod(d.month + offset_months, 12)	
	d2 = date(d.year+q, r+1, 1) - one_day
	
	if d.month != (d+one_day).month:
		return d2
		
	if d.day >= d2.day:
		return d2
		
	return d2.replace(day=d.day)
	
	